
import Taro, { Component } from "@tarojs/taro";
import { connect } from "@tarojs/redux";
import _isEmpty from 'lodash/isEmpty';
import { View, Image, Text, Textarea } from '@tarojs/components';
import { AtCountdown, AtNoticebar, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtTextarea } from 'taro-ui';
import { getPayDownTime, getWaitingTime, getOrderDownTime, checkOrderOver20} from '../../utils'
import { userInfoList } from "../../utils/mock";

import AddressLine from "../../components/AddressLine";
import AddressItem from "../../components/AddressItem";
import BaseButton from "../../components/BaseButton";
import GModal from "../../components/GModal";
import StepItem from "../../components/StepItem";
import RadioItem from "@/components/RadioItem";
import { ModalBottom } from '../../components/CustomModal'

import contact_img from '../../assets/order_contact.png'
import cancel_img from '../../assets/order_cancel.png'

import TIM from 'tim-js-sdk';
import tim from '../../utils/tim';
import './index.scss';

@connect(({ order, common }) => ({
  orderInfo: order.orderInfo,
  common
}))
class OrderDetail extends Component {

  config = {
    navigationBarTitleText: '订单详情'
  };

  constructor(props) {
    super(props);
    this.state = {
      waitShow: false,
      extraShow: false,
      cancelText: '',
      receiveShow: false,
      rInfo: {},
      isOver: false,
      cancelModal: false,
      rejectList: [],
      rejectItem: {},
      rejectRemark: ''
    };
    this.timer = 0
  }


  componentDidMount() {
    this.getOrderDetail()
  }

  componentWillReceiveProps(nextProps) {
    const { orderInfo } = nextProps;
    if (!_isEmpty(orderInfo)) {
      this.setState({ rInfo: orderInfo })
    }
  }

  componentWillUnmount(){
    clearInterval(this.timer)
  }

  render() {
    const { cancelModal, rInfo, rejectList, rejectItem, rejectRemark } = this.state
    const lineData = !_isEmpty(rInfo) ? {
      type: rInfo.trafficTypeCode,
      typeCn: rInfo.trafficTypeCn,
      lineStart: rInfo.carrierLineStart,
      lineEnd: rInfo.carrierLineEnd,
      sender: rInfo.users[0].type === 'sender' ? rInfo.users[0].linkman : rInfo.users[1].linkman,
      receiver: rInfo.users[0].type === 'receiver' ? rInfo.users[0].linkman : rInfo.users[1].linkman,
    } : {}
    const againOrder = (rInfo.orderStatusCode === 'publish_cancel' || rInfo.orderStatusCode === 'taking_cancel' || rInfo.orderStatusCode === 'overtime_close' || rInfo.orderStatusCode === 'system_close' )

    const contentHeight = !againOrder && rInfo.orderStatusCode !== 'taking' && rInfo.orderStatusCode !== 'waittaking' ? 'calc(100vh - 80PX)' : '95vh'

    const hideEle = false
    const addStr = this.handleAddedServiceText()
    return <View className="order-detail-page">
      {!_isEmpty(rInfo) && <View className='detail-content' style={{ height: contentHeight }}>
        <View className='top-content'>
          {hideEle ? <View className='top-content-cancel'>
            <View>
              <View>接单已取消</View>
              <View className='top-content-cancel-subtext'>取消原因：仓位已满</View>
              <View className='top-content-cancel-time'>取消时间：2020-04-17 15:33:46</View>
            </View>
            <BaseButton text='重新下单' type='primary' width={100} height={36} onClick={() => this.handleOrderButton('reorder')}/>
          </View> :  <View className='top-content-title'>
            <View>订单号:{rInfo.orderNumber}</View>
            <View>{rInfo.orderStatusCn}</View>
          </View>}
          <View className='address-line-content' style={{padding: '0 20px'}}>
            <AddressLine data={lineData} traType={rInfo.trafficTypeCode}/>
          </View>
        </View> 

        {!_isEmpty(rInfo) && !_isEmpty(rInfo.logs) &&<View className='log-content'>
          {rInfo.logs.map((ld, i) => {
            return (<StepItem key={ld.id} data={ld} active={i===0} border={i!==0}/>)
          })}
        </View>}
        {(rInfo.orderStatusCode === 'wait_taking'||rInfo.orderStatusCode === 'taking'||rInfo.orderStatusCode === 'trafficing'||rInfo.orderStatusCode === 'finish') && <View className='operate-content'>
          {(rInfo.orderStatusCode === 'wait_taking'|| rInfo.orderStatusCode === 'taking') ? <View className='operate-content-item' onClick={() => this.handleCancelModal(true)}>
            <Image className='operate-content-item-img' src={cancel_img}></Image>
            <Text>取消订单</Text>
          </View> : <View className='operate-content-item'/>}
          {(rInfo.orderStatusCode === 'taking'||rInfo.orderStatusCode === 'trafficing'||rInfo.orderStatusCode === 'finish') && hideEle ? <View className='operate-content-item'>
            <Image className='operate-content-item-img' src={contact_img}></Image>
            <Text>与Ta联系</Text>
          </View> : <View className='operate-content-item' />}
        </View>}

        <View className='info-content'>
          <AddressItem info={rInfo.users[0]}/>
          <AddressItem isSend={false} info={rInfo.users[1]}/>
          <View className='info-content-list'>
            <View>品名：{rInfo.goods.goodsName}</View>
            <View>品类：{rInfo.goods.goodsTypeCn}</View>
            <View>件数：{rInfo.goods.goodsNum}</View>
            <View>重量：{rInfo.goods.goodsWeight}</View>
            <View>体积：{rInfo.goods.goodsBulk}</View>
            {rInfo.goods.goodsLength && rInfo.goods.goodsWidth && rInfo.goods.goodsHeight && <View className='info-content-list-row'>长宽高：{rInfo.goods.goodsLength}x{rInfo.goods.goodsWidth}x{rInfo.goods.goodsHeight}cm</View>}

            <View className='info-content-list-row'>备注信息：{rInfo.orderRemark}</View>

            <View>声明价值：{rInfo.extras.statementPrice}</View>
            <View>保价费：{rInfo.extras.premium}</View>
            {rInfo.extras.priceDetails && !_isEmpty(rInfo.extras.priceDetails) && rInfo.extras.priceDetails.map(pd => {
              let text = pd.value
              if(typeof(pd.value) === 'number'){
                text = `￥${pd.value}`
              }
              return (<View>{pd.name}：{text}</View>)
            })}
       
            <View>运费：{rInfo.orderPrice}元</View>
            <View>发货类型：{rInfo.extras.deliverTypeCn}</View>
            {rInfo.dispatch.sendTypeCn && <View>寄件方式：{rInfo.dispatch.sendTypeCn}</View>}
            {rInfo.dispatch.visitGoodsTime && <View>上门取件时间：{rInfo.dispatch.visitGoodsTime}</View>}

            <View>派送方式：{rInfo.dispatch.receiveTypeCn}</View>
            {rInfo.dispatch.hopeArrvialTim && <View>期望到达时间：{rInfo.dispatch.hopeArrvialTime}</View>}
            
            <View className='info-content-list-row'>增值服务：{
              addStr.list.map(ad => {
                return (<Text>{ad.name}</Text>)
              })
            }</View>
          </View>
        </View>
      </View>}
      {!againOrder && rInfo.orderStatusCode !== 'taking' && rInfo.orderStatusCode !== 'waittaking' && <View className='bottom-content order-detail-bottom'>
        {rInfo.orderStatusCode === 'taking' && <BaseButton text='打印订单' type='secondary' width={120} onClick={() => this.handleOrderButton('print')}/>}
        {rInfo.orderStatusCode === 'goods_stop' && <BaseButton text='重新下单' type='secondary' width={120} onClick={() => this.handleOrderButton('reorder')}/>}
        {rInfo.orderStatusCode === '' && <BaseButton text='修改地址' type='secondary' width={120} onClick={() => this.handleOrderButton('changeaddress')}/>}
        {rInfo.orderStatusCode === 'finish' && <BaseButton text='评价' type='secondary' width={120} onClick={() => this.handleOrderButton('evaluate')}/>}
        {rInfo.orderStatusCode === 'finish' && <BaseButton text='确认回单' type='secondary' width={120} onClick={() => this.handleOrderButton('recipt')}/>}
      </View>}
      <ModalBottom
        isOpened={cancelModal}
        onClose={() => this.handleCancelModal(false)}
        renderFooter={(<View className='modal-content-btns'>
          <BaseButton cls='modal-content-btn' text='暂不取消' type='primary' circle={false} width='50%' onClick={() => this.handleCancelModal(false)}/>
          <BaseButton text='确认取消' type='primary' circle={false}  width='50%' onClick={this.handleCancelOrder}/>
        </View>)}
      >
        <View className='cancel-warn'>{rInfo.orderStatusCode === 'wait_taking' ? '取消订单后，全款将退回付款账户。' : '取消订单后，将扣除订舱费xx元，（如果在条件范围内）剩余金额将退回到付款账户'}</View>
        <View className='cancel-title'>请选择取消订单原因</View>
        <View className='cancel-reason-list'>
          {!_isEmpty(rejectList) && rejectList.map(rl => {
            const active = rl.id === rejectItem.id
            return (<RadioItem title={rl.name} height={40} isLeft={false} jsContent='space-between' checked={active} onClick={() => this.handleSelectReject(rl)}/>)
          })}
          {rejectItem.code === 'other_fd' && <AtTextarea
            rows={3}
            value={rejectRemark}
            placeholder='请输入其他原因'
            onChange={this.cancaelResonInput}
          ></AtTextarea>}
        </View>
      </ModalBottom>
    </View>;
  }

  
  /** 订单状态，按钮操作 */
  handleOrderButton = (type) => {
    const { rInfo } = this.state
    switch (type) {
      case 'print':
        console.log('打印订单')
        break;
      case 'reorder':
        console.log('重新下单')
        // Taro.navigateTo({ url: `/pages/order/index?type=air_traffic`})
        break;
      case 'changeaddress':
        console.log('修改地址')
        break;
      case 'evaluate':
        console.log('评价')
        break;
      case 'recipt':
        console.log('确认回单')
        break;
      default:
        break;
    }
    conosle.log('===打印订单===')
  }

  // TODO: 分情况显示取消弹框
  handleCancelModal = (flag) => {
    this.setState({ cancelModal: !!flag })
    if(!flag){
      this.setState({
        rejectItem: {},
        rejectRemark: ''
      })
    }
  }
  /** 取消原因选择 */
  handleSelectReject = (item) => {
    this.setState({ 
      rejectItem: item,
      rejectRemark: '',
    })
  }

  /** 其他原因 */
  cancaelResonInput = (e) => {
    this.setState({ rejectRemark: e })
  }
  /** 取消订单确认 */
  handleCancelOrder = () => {
    console.log('==取消订单==')
    const { rejectItem, rejectRemark, rInfo } = this.state
    const { dispatch } = this.props
    
    let params = {
      orderId: rInfo.id,
      orderStatusCode: 'publish_cancel',
      desc: rejectItem.name
    }
    if(rejectItem.code === 'other_fd'){
      params.desc = rejectRemark
    }
  }

  toChatPage = () => {
    const { rInfo } = this.state
    Taro.navigateTo({ url: '/pages/mynews/chat/index?uId='+rInfo.takingUserId})
  }

  showOrderImage = (index) => {
    const { rInfo } = this.state
    Taro.previewImage({urls: rInfo.orderImage, current: rInfo.orderImage[index]})
  }

  toCancelOrder = () => {
    console.log('取消订单');
    const { dispatch } = this.props;
    const { rInfo } = this.state;
    const params = {
      orderId: rInfo.id,
      stateEn: 'close'
    };
   
    this.showWaitModal(false);
  };

  /** 重新下单 */
  toAgainOrder = () => { 
    const { rInfo } = this.state
    // Taro.navigateTo({url: `/pages/orderedit/index?rId=${rInfo.id}`})
  };

  showExtraModal = (flag) => {
    this.setState({ extraShow: !!flag })
  }
  /**额外费用支付 */
  toExtraPayOrder = () => {
    const { rInfo } = this.state;
    const { dispatch } = this.props;
    const params = {
      orderId: rInfo.id,
      stateEn: 'extra_success',
      needOrderAddedMoney: true,
      orderAddedMoney: rInfo.orderAddedMoney

    };
    this.setState({ extraShow: false })
   
  };

  /** 去评价 */
  toRateOrder = () => {
    const rId = this.$router.params.rId;
    Taro.navigateTo({ url: `/pages/rateorder/index?rId=${rId}` });
  };

  /** 取消订单modal */
  showWaitModal = flag => {
    const { rInfo } = this.state;
    if (rInfo.orderStatusEn === 'processes') {
      this.setState({
        cancelText: '取消订单后，费用将退回到付款账号'
      });
    } else {
      this.setState({
        cancelText: ''
      });
    }
    this.setState({ waitShow: !!flag });
  };

  showReceiveModal = flag => {
    this.setState({ receiveShow: !!flag });
  };

  getOrderDetail = () => {
    const rId = this.$router.params.rId;
    const { dispatch } = this.props;
  };
 
  /** 处理增值服务显示 */
  handleAddedServiceText = () => {
    const { rInfo } = this.state
    let hasBus = false
    let tlist = []
    if(rInfo && !_isEmpty(rInfo) && !_isEmpty(rInfo.extras) && !_isEmpty(rInfo.extras.addedServices)){
      const sdata = rInfo.extras.addedServices
      sdata.forEach(ad => {
        let clist = []
        hasBus = ad.code === 'urgent_air'
        if(ad.childServices && !_isEmpty(ad.childServices)){
          ad.childServices.forEach(cd => {
            clist.push(cd)
          })
        }
        
        tlist = [...tlist, ad, ...clist]
      })
    }
    return { list: tlist, hasBus }
  }
}

export default OrderDetail;